<template>
  <div class="stock-manage">
    <el-container>
      <el-main>
        <div class="page-header">
          <h1>库存管理</h1>
          <el-button type="primary" @click="openAdd">新增库存</el-button>
        </div>

        <el-card>
          <div class="toolbar">
            <el-input
              v-model="keyword"
              placeholder="搜索商品名称"
              style="max-width: 260px"
              clearable
            />
            <el-button type="primary" @click="filterStocks">搜索</el-button>
            <el-button type="danger" :disabled="!selected.length" @click="batchDelete"
              >批量删除</el-button
            >
          </div>
          <el-table :data="paginatedStocks" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="商品名称" width="200">
              <template #default="{ row }">
                {{ row.shoes?.name || '未知商品' }}
              </template>
            </el-table-column>
            <el-table-column label="尺码" width="100">
              <template #default="{ row }">
                {{ row.size?.shoeSize || '未知尺码' }}
              </template>
            </el-table-column>
            <el-table-column label="颜色" width="100">
              <template #default="{ row }">
                {{ row.color?.colorName || '未知颜色' }}
              </template>
            </el-table-column>
            <el-table-column label="价格" prop="price" width="100" />
            <el-table-column label="折扣价" prop="discountPrice" width="100" />
            <el-table-column label="库存数量" prop="stockQuantity" width="120" />
            <el-table-column label="操作" width="220">
              <template #default="{ row }">
                <el-button size="small" @click="openEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="handleDelete(row.shoeId, row.sizeId)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pager">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-size="pageSize"
              :current-page="page"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>

    <el-dialog
      :title="editing ? '编辑库存' : '新增库存'"
      :model-value="dialogVisible"
      :width="isMobile ? '95vw' : '520px'"
      @close="closeDialog"
      :class="{ 'mobile-dialog': isMobile }"
    >
      <el-form :model="form" label-width="90px" :class="{ 'mobile': isMobile }">
        <el-form-item label="商品ID">
          <el-input 
            v-model.number="form.shoeId" 
            type="number" 
            :size="isMobile ? 'large' : 'default'"
          />
        </el-form-item>
        <el-form-item label="尺码ID">
          <el-input 
            v-model.number="form.sizeId" 
            type="number" 
            :size="isMobile ? 'large' : 'default'"
          />
        </el-form-item>
        <el-form-item label="颜色ID">
          <el-input 
            v-model.number="form.colorId" 
            type="number" 
            :size="isMobile ? 'large' : 'default'"
          />
        </el-form-item>
        <el-form-item label="价格">
          <el-input 
            v-model.number="form.price" 
            type="number" 
            :size="isMobile ? 'large' : 'default'"
          />
        </el-form-item>
        <el-form-item label="折扣价">
          <el-input 
            v-model.number="form.discountPrice" 
            type="number" 
            :size="isMobile ? 'large' : 'default'"
          />
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input 
            v-model.number="form.stockQuantity" 
            type="number" 
            :size="isMobile ? 'large' : 'default'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" :class="{ 'mobile': isMobile }">
          <el-button 
            @click="closeDialog"
            :size="isMobile ? 'large' : 'default'"
            class="cancel-btn"
          >
            取消
          </el-button>
          <el-button 
            type="primary" 
            @click="submit"
            :size="isMobile ? 'large' : 'default'"
            class="save-btn"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { productService } from '@/api'

type StockRow = {
  skuId?: number
  shoeId: number
  sizeId: number
  colorId: number
  price: number
  discountPrice?: number
  stockQuantity: number
  shoes?: { name: string }
  size?: { shoeSize: string }
  color?: { colorName: string }
}

const loading = ref(false)
const stocks = ref<StockRow[]>([])
const selected = ref<StockRow[]>([])
const total = ref(0)

const dialogVisible = ref(false)
const editing = ref(false)
const form = ref<Partial<StockRow>>({ shoeId: 0, sizeId: 0, stockQuantity: 0 })
let editingKey: { shoeId: number; sizeId: number } | null = null
// 分页相关状态
const page = ref(1)
const pageSize = ref(10)
const keyword = ref('')

// 移动端判断
const isMobile = computed(() => window.innerWidth < 768)

// 过滤后的库存列表
const filteredStocks = computed(() => {
  if (!keyword.value) return stocks.value
  return stocks.value.filter(stock => 
    stock.shoes?.name?.toLowerCase().includes(keyword.value.toLowerCase()) ||
    stock.size?.shoeSize?.toLowerCase().includes(keyword.value.toLowerCase()) ||
    stock.color?.colorName?.toLowerCase().includes(keyword.value.toLowerCase())
  )
})

// 分页后的库存列表
const paginatedStocks = computed(() => {
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredStocks.value.slice(start, end)
})

const loadList = async () => {
  loading.value = true
  try {
    const res = await productService.getStockListPage(page.value, pageSize.value, keyword.value || undefined, undefined, undefined, undefined)
    if (res.data.code === 200) {
      const data = res.data.data
      if (data) {
        stocks.value = data.list || []
        total.value = data.total || 0
      }
    }
  } finally {
    loading.value = false
  }
}

const openAdd = () => {
  editing.value = false
  editingKey = null
  form.value = { shoeId: 0, sizeId: 0, colorId: 0, price: 0, discountPrice: 0, stockQuantity: 0 }
  dialogVisible.value = true
}

const openEdit = (row: StockRow) => {
  editing.value = true
  editingKey = { shoeId: row.shoeId, sizeId: row.sizeId }
  form.value = {
    shoeId: row.shoeId,
    sizeId: row.sizeId,
    colorId: row.colorId,
    price: row.price,
    discountPrice: row.discountPrice,
    stockQuantity: row.stockQuantity,
  }
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
}

const submit = async () => {
  if (editing.value && editingKey) {
    await productService.updateStock(form.value as any)
  } else {
    await productService.addStock(form.value as any)
  }
  dialogVisible.value = false
  loadList()
}

const handleDelete = async (shoeId: number, sizeId: number) => {
  await productService.deleteStock(shoeId, sizeId)
  loadList()
}

const handleSelectionChange = (rows: StockRow[]) => {
  selected.value = rows
}

const batchDelete = async () => {
  if (!selected.value.length) return
  await Promise.all(
    selected.value.map((item) => productService.deleteStock(item.shoeId, item.sizeId)),
  )
  selected.value = []
  await loadList()
}

// 分页处理函数
const filterStocks = () => {
  page.value = 1 // 搜索时重置到第一页
  loadList()
}

const handlePageChange = (val: number) => {
  page.value = val
  loadList()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  page.value = 1 // 每页显示条数改变时，重置当前页为1
  loadList()
}

onMounted(loadList)
</script>

<style scoped>
.stock-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.toolbar {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

/* 移动端适配样式 */
@media (max-width: 768px) {
  .stock-manage {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .toolbar {
    flex-wrap: wrap;
    gap: 8px;
    
    .el-button {
      flex: 1;
      min-width: 120px;
      height: 44px;
      font-size: 14px;
    }
  }
  
  .el-table {
    .el-table__header,
    .el-table__body {
      font-size: 14px;
    }
    
    .el-button {
      height: 36px;
      font-size: 14px;
      border-radius: 6px;
    }
  }
  
  .el-form {
    &.mobile {
      .el-form-item {
        margin-bottom: 20px;
        
        .el-form-item__label {
          font-size: 14px;
          font-weight: 500;
          margin-bottom: 8px;
        }
        
        .el-input {
          .el-input__inner {
            height: 44px;
            font-size: 16px;
            border-radius: 8px;
          }
        }
      }
    }
  }
}

/* 移动端对话框样式 */
:deep(.mobile-dialog) {
  .el-dialog {
    margin: 10px auto !important;
    border-radius: 16px;
    
    .el-dialog__header {
      padding: 20px 20px 16px;
      
      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
      }
    }
    
    .el-dialog__body {
      padding: 0 20px 20px;
    }
    
    .el-dialog__footer {
      padding: 0 20px 20px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  &.mobile {
    flex-direction: column;
    gap: 10px;
    
    .el-button {
      width: 100%;
      height: 48px;
      font-size: 16px;
      border-radius: 8px;
      font-weight: 500;
    }
  }
  
  .cancel-btn {
    background-color: #f5f7fa;
    border-color: #dcdfe6;
    color: #606266;
    font-weight: 500;
    
    &:hover {
      background-color: #ebeef5;
      border-color: #dcdfe6;
      color: #409eff;
    }
  }
  
  .save-btn {
    background-color: #409eff;
    border-color: #409eff;
    color: #fff;
    font-weight: 500;
    
    &:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
      color: #fff;
    }
  }
}

/* 平板端优化 */
@media (min-width: 769px) and (max-width: 1024px) {
  .stock-manage {
    padding: 16px;
  }
  
  .el-form {
    .el-form-item {
      margin-bottom: 18px;
      
      .el-form-item__label {
        font-size: 14px;
      }
    }
  }
  
  .el-table {
    .el-button {
      height: 32px;
      font-size: 13px;
    }
  }
}
</style>
